<template>
  <div class="page-main" v-title data-title="素材制作订单">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container" ref="imageWrapper">
      <div class="head-content">
        <span class="bold-font">素材制作订单</span>
        <div class="btn-line">
          <a-button class="hte-btn add-btn" type="primary" v-if="submitBtnShow" :loading="btnLoading" @click="onSubmitForm">提交审批</a-button>
          <a-button class="hte-btn add-btn" type="primary" v-if="evaluateBtnShow" :loading="btnLoading" @click="onSubmitForm">提交评价</a-button>
          <a-button class="hte-btn" v-if="saveBtnShow" :loading="btnLoading" @click="saveData">保存</a-button>
          <a-button class="hte-btn" type="danger" v-if="delBtnShow" :loading="btnLoading" @click="deleteOrder">删除</a-button>
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <section>
            <div class="section-header">订单基础信息
              <div class="btn-line" v-if="!!form.status&&form.status>1&&form.status<5">
                <span style="color: red;font-size: 14px;">
                {{'进行中订单数量：'+designingCount+"，请耐心等候"}}
              </span>
              </div>
            </div>
            <template>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="订单号">
                    <a-input v-model="form.orderNo" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请人/部门">
                    <a-input v-model="form.applyInfo" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请时间">
                    <a-input v-model="form.applyTime" disabled/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="16">
                  <a-form-model-item label="订单名称" prop="orderName">
                    <a-input v-model="form.orderName" maxlength="125" placeholder="请输入" :disabled="form.status>1||(form.status==2 && !isCanEdit)"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="产品信息" prop="productInfo">
                    <a-input v-model="form.productInfo" placeholder="例“0金标生抽 500ml”,不涉及填“无”" :disabled="form.status>1||(form.status==2&&!isCanEdit)"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="订单类型" prop="orderType">
                    <a-select v-model="form.orderType" placeholder="请选择" @change="orderTypeChange" :disabled="form.status>1||(form.status==2&&!isCanEdit)">
                      <a-select-option v-for="(item, index) in dict.orderTypeList" :key="index" :value="item.code">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="制作内容" prop="displayMode">
                    <a-select v-model="form.displayMode" placeholder="未有或不清楚选择“其他”" :disabled="form.status>1||(form.status==2&&!isCanEdit)">
                      <a-select-option v-for="(item, index) in dict.displayModeList" :key="index" :value="item.code">
                        {{item.name}}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="应用渠道" prop="useType">
                    <a-select v-model="form.useType" placeholder="请选择" :disabled="form.status>1||(form.status==2&&!isCanEdit)">
                      <a-select-option v-for="(item, index) in dict.useTypeList" :key="index" :value="item.code">
                        {{item.name}}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-tooltip placement="top" arrow-point-at-center>
                    <template slot="title">
                      平面设计订单、平面设计审核：竖版60cmx90cm；<br/>视频制作订单、视频制作审核：横版16:9；<br/>电商详情页：竖版长图。
                    </template>
                    <a-form-model-item label="规格尺寸" prop="specs">
                      <a-input v-model="form.specs" placeholder="请输入规格，如：竖版60cmx90cm、横版16:9、竖版长图" :disabled="form.status>1||(form.status==2&&!isCanEdit)"/>
                    </a-form-model-item>
                  </a-tooltip>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="文件格式" prop="fileFormat">
                    <a-input v-model="form.fileFormat" placeholder="请输入" :disabled="form.status>1||(form.status==2&&!isCanEdit)"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="期望完成时间" prop="expectFinishTime">
                    <a-date-picker valueFormat="YYYY-MM-DD HH:mm:ss" v-model="form.expectFinishTime" placeholder="请选择" :disabled="form.status>1||(form.status==2&&!isCanEdit)"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="费用支出号" prop="costCenterNo">
                    <a-input type="integer" v-model="form.costCenterNo" placeholder="请输入" :disabled="form.status>1||(form.status==2&&!isCanEdit)"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="经济事项" prop="economyItem">
                    <a-input v-model="form.economyItem" placeholder="请输入" :disabled="form.status>1||(form.status==2&&!isCanEdit)"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-model-item
                    label="补充说明"
                    prop="orderMemo"
                  >
                    <a-textarea
                      v-model="form.orderMemo"
                      placeholder="说明订单设计需求(限200字)，如果有更多要求信息或资料，请在下方上传附件。"
                      :auto-size="{ minRows: 2 }"
                      maxlength="200"
                      :disabled="form.status>1||(form.status==2&&!saveBtnShow)"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </template>
            <template>
              <div class="section-header mt15">
                <div>附件上传<span class="em">必须上传附件才能提交流程，请下载模板完善设计需求信息，然后先保存表单再上传附件。</span></div>
              </div>
              <div class="section-table">
                <div class="btn-line">
                  <a-button class="hte-btn" @click="handAction('downloadMould')">下载模板</a-button>
                  <template>
                    <ht-upload
                      v-if="form.id"
                      v-show="showFileBtn"
                      ref="myUpload"
                      class="upload-demo"
                      multiple
                      dbKey="Trd"
                      busField="require"
                      busType="libMediaOrder"
                      :busKey="form.id.toString()"
                      ftpKey="ftp"
                      v-model="fileData"
                      :show-file-list="false"
                      :before-upload="(value) => beforUpload(value, 'fileData')"
                    >
                      <a-button class="hte-btn add-btn" type="primary" icon="plus">上传</a-button>
                    </ht-upload>
                    <a-button v-else class="hte-btn add-btn" type="primary" icon="plus" @click="remainSave">上传</a-button>
                  </template>
                  <a-button class="hte-btn" @click="handAction('download')">下载</a-button>
                  <a-button class="hte-btn" @click="handAction('del')" v-show="showFileBtn">删除</a-button>
                </div>
                <div>
                  <a-table
                    class="hte-table-content"
                    :columns="fileColumns"
                    :data-source="fileData"
                    :pagination="false"
                    :loading="tabLoading"
                    rowKey="id"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                    bordered
                    size="middle"
                  >
                    <template slot="fileName" slot-scope="text, record">
                      <a-button type="link"  @click="previewAttach(record)">{{ record.fileName }}</a-button>
                    </template>
                  </a-table>
                </div>
              </div>
            </template>
          </section>
          <section id="makeInfoDiv">
            <div v-if="showMakeInfo" >
              <div class="section-header">制作信息</div>
              <template>
                <a-row :gutter="24">
                  <a-col :span="8" v-if="isMediaAdmin||form.status==3 && saveBtnShow && currentTaskDefKey=='orderDispatch'">
                    <a-form-model-item label="设计安排" prop="designArrange">
                      <a-radio-group name="radioGroup" v-model="form.designArrange" @change="designArrangeChange" :disabled="!(form.status == 3 &&saveBtnShow && currentTaskDefKey=='orderDispatch')">
                        <a-radio value="1"> 内部 </a-radio>
                        <a-radio value="2"> 委外 </a-radio>
                      </a-radio-group>
                    </a-form-model-item>
                  </a-col>
                  <!-- <a-col :span="8" v-if="form.designArrange=='1'&&(isMediaAdmin||form.status==3&&saveBtnShow&&saveBtnShow&&currentTaskDefKey=='orderDispatch')"> -->
                    <a-col :span="8">
                    <a-form-model-item label="内部设计师" prop="designer" ref="designer">
                      <a-select
                        show-search
                        :value="form.designerName"
                        placeholder="请输入"
                        style="width: 100%"
                        :filter-option="false"
                        :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                        @search="fetchTestUser"
                        @change="(val,option) => {fetchTestChange(val,option, 'designerName', 'designer')}"
                        :disabled="!(form.status==3 && saveBtnShow && currentTaskDefKey=='orderDispatch')"
                      >
                        <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                        <a-select-option v-for="(d, index) in userTestData" :key="index" :value="d.username">
                          {{ d.realname }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" v-if="form.designArrange=='2'">
                    <a-form-model-item label="设计单位" prop="designSupplier">
                      <a-input v-model="form.designSupplier" placeholder="请输入"  :disabled="!(form.status==3 &&saveBtnShow&&currentTaskDefKey=='orderDispatch')"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" v-if="this.form.orderType!='3'">
                    <a-form-model-item label="制作服务费(元)" prop="designerCost">
                      <a-input-number prefix="￥" suffix="RMB" v-model="form.designerCost" placeholder="请输入"  :disabled="!(form.status==2&&saveBtnShow)" :precision="2"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="制作方式" prop="makeWay">
                      <a-radio-group name="radioGroup" v-model="form.makeWay"  :disabled="!(form.status==2 && saveBtnShow)">
                        <a-radio value="1"> 原创 </a-radio>
                        <a-radio value="2"> 改版 </a-radio>
                        <a-radio value="3"> 调整 </a-radio>
                      </a-radio-group>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="计划完成时间" prop="planFinishTime">
                      <a-date-picker valueFormat="YYYY-MM-DD HH:mm:ss" v-model="form.planFinishTime" placeholder="请选择"  :disabled="!(form.status==2&&saveBtnShow)"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8" v-if="isMediaAdmin||form.status==2&&saveBtnShow">
                    <a-form-model-item label="标准工时(h)" prop="workingHours">
                      <a-input-number v-model="form.workingHours" placeholder="素材完成所需工作时常，单位为小时"  :disabled="!(form.status==2&&saveBtnShow)"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="修改次数" prop="modifyTimes" v-if="isMediaAdmin||form.status==3&&currentTaskDefKey=='mediaMaking'" >
                      <a-input-number v-model="form.modifyTimes" :min="0" placeholder="请输入"  :disabled="!(form.status==3&&currentTaskDefKey=='mediaMaking')"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="实际完成时间"  prop="realFinishTime" v-if="isMediaAdmin">
                      <a-date-picker valueFormat="YYYY-MM-DD HH:mm:ss" v-model="form.realFinishTime" disabled/>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row :gutter="24" v-if="!!form.status&&form.status==7">
                  <a-col :span="24">
                    <a-form-model-item label="作废说明"  prop="cancelMemo">
                      <a-textarea v-model="form.cancelMemo" :auto-size="{ minRows: 2 }" disabled />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </template>
            </div>

            <div>
              <template  v-if=" ['4' , '5'].includes(form.orderType) || showMakeInfo">
                <div class="section-header mt15">
                  <div>素材上传</div>
                </div>
                <div class="section-table">
                  <div>
                    <hte-upload
                                v-if="form.id"
                                ref="mediaAttach" dbKey="Trd"
                                busField="media"
                                :busKey="form.id"
                                :uploadDisabled="!(saveBtnShow)"
                                :deleteDisabled="!(saveBtnShow)"
                                :previewDisabled="false"
                                :downloadDisabled="true"
                                :refreshDisable="true"
                                busType="libMediaOrder"
                                ftpKey="ftpMedia"
                                :onPreview="previewAttach"
                                :zipFileName="form.orderNo+'素材.zip'">
                    </hte-upload>
                    <!--:onSuccess="(response,file,fileList)=>fileUploadSuccess(response,file,fileList,drawingAttache.code)"
                    :onRemove="(idsArr,selectionRows)=>deleteDrawing(idsArr,selectionRows,drawingAttache.code)"-->
                    <a-button v-else class="hte-btn add-btn" type="primary" icon="plus" @click="remainSave">上传</a-button>
                  </div>
                </div>
              </template>
            </div>

            <template v-if="!!form.status&&form.status>3">
              <div class="section-header mt15">
                满意度评价
              </div>
              <template>
                <a-row :gutter="24">
                  <a-col :span="8">
                    <a-form-model-item label="用户评价"  prop="evaluationScore">
                      <span class="ratebox">
                        <a-rate v-model="form.evaluationScore" :tooltips="rateDesc" :disabled="!evaluateBtnShow"/>
                        <span class="ant-rate-text">{{ rateDesc[form.evaluationScore-1] }}</span>
                      </span>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="16">
                    <a-form-model-item label="意见反馈"  prop="suggestion">
                      <a-input v-model="form.suggestion" placeholder="请填写您的宝贵意见，您的意见将是我们前进的动力！" :disabled="!evaluateBtnShow"/>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </template>
            </template>
          </section>
          <section v-if="!!processInstanceId&&processInstanceId!=''">
            <div class="section-header">流程信息</div>
            <template>
              <ht-approval
                ref="childrenRef"
                :process-instance-id="processInstanceId"
                :options="options"
                :custom="custom"
                @submit="afterSubmit"
                @reject="afterReject"
                @back="backAction"
                @cancelSubmit="afterCancelSubmit"
                :before-fill-opinion="saveNotifyOpinion"
                :before-submit="beforeSubmit"
                :before-reject="beforeReject"
                :show-task-history="true"
                :history-dialog="historyDialog"
                :task-load="taskLoad"
                :message-id="messageId"
                :show-upload-btn="false"
                :return-revert-node-flag="1"
                :hidden-task-def-key="hiddenTaskDefKey"
                :snapshotConfigs="snapshotConfigs"
              >
              </ht-approval>
            </template>
          </section>
        </a-form-model>
        <div class="btn-bottom-fixed">
          <a-button class="hte-btn add-btn" type="primary" v-if="submitBtnShow" :loading="btnLoading" @click="onSubmitForm">提交审批</a-button>
          <a-button class="hte-btn add-btn" type="primary" v-if="evaluateBtnShow" :loading="btnLoading" @click="onSubmitEvaluate">提交评价</a-button>
          <a-button class="hte-btn" v-if="saveBtnShow" :loading="btnLoading" @click="saveData">保存</a-button>
          <a-button class="hte-btn" type="danger" v-if="delBtnShow" :loading="btnLoading" @click="deleteOrder">删除</a-button>
        </div>
      </div>
    </div>
    <process-user-select
      :columns="userForm.submitUserCols"
      :winHeight="150"
      :winWidth="550"
      :targetKeys="userForm.proOriginTargetKeys"
      @selectUserConfirm="selectUserConfirm"
      ref="processUserSelect"
    />

    <a-modal
      title="请确定"
      :visible="lawVisible"
      :width="750"
      :height="600"
      :footer="null"
    >
      <span>请确认本次是否做了修改? 选是则 【修改次数】数据自增1。</span>
      <div style="text-align:center">
        <a-button   style="margin:10px 0;" @click="handleConfirm(0)">否</a-button>
        <a-button  type="primary"  style="margin:10px 0;margin-left: 10px" @click="handleConfirm(1)">是</a-button>
      </div>
    </a-modal>

  </div>
</template>
<script>
const validateMobile = (rule, value, callback) => {
  let reg = /^1(3|4|5|7|8)\d{9}$/
  if (!reg.test(value)) {
    callback('请输入正确手机号')
  } else {
    callback()
  }
};
const validateInteger = (rule, value, callback) => {
  let reg = /^[1-9][0-9]*$/
  if (!reg.test(value)) {
    callback('只能输入数字')
  } else {
    callback()
  }
};
const validateChinese = (rule, value, callback) => {
  let reg = /[\u4e00-\u9fa5]/g
  if (!reg.test(value)) {
    callback('订单名称必须包含中文')
  } else {
    callback()
  }
};
import {getAction, postAction, previewAttach} from '@/api/manage';
import Vue from 'vue';
import '@/utils/upload.install.js';
import '@/config/hteupload.install.js';
import {ACCESS_TOKEN, USER_NAME} from '@/store/mutation-types'
import {codeInfoList,codeInfoByTypeAndParent} from '@/api/codeInfo'
import {Modal} from 'ant-design-vue'
import {formatSize, isPreview} from '@/components/hteUpload/common/utils'
import {downloadAttach} from '@/components/hteUpload/api/upload'
import {Base64} from 'js-base64'
import {filterHasPermission} from '@/utils/hasPermission'

export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    ProcessUserSelect: () => import('@/components/tools/projectBuildStup/ProcessUserSelect'),
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
  },
  props:{
    isReject:{
      type:Boolean ,
      required: false
    } ,

  } ,
  data() {
    return {

      isCanUploadMaterial:false ,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'MediaOrderInfo',
      },
      id:this.$route.query.id,
      depLeader:{},
      isMediaAdmin:false,
      processInstanceId:'',
      options: {
        request: {
          baseUrl: this.API_BASE_URL, // 业务系统根路径
          timeOut: 10000, // 请求超时时间
          interceptors: (config) => {
            config.headers['X-Access-Token'] = Vue.ls.get(ACCESS_TOKEN)
            return config
          },
        },
        userId: Vue.ls.get(USER_NAME),
      },
      messageId: '', // 工作台URL里面的msgId参数
      hiddenTaskDefKey: 'submit',
      custom: {},
      lawVisible : false ,
      historyDialog: {
        // 审批历史模态框属性
      },
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper'
        }
      ],
      currentTaskDefKey:'',
      currentAuditUser:'',
      dict: {
        orderTypeList: [], // 素材类型
        displayModeList: [],  // 展示形式
        useTypeList: [], // 应用类型
      },
      form: {},
      btnLoading:false,
      saveBtnShow:false,
      delBtnShow:false,
      submitBtnShow:false,
      evaluateBtnShow:false,
      rules:{},
      baseInfoRules: {
        orderName: [{ required: true, message: '请输入订单名称', trigger: 'blur'},
          { min: 3, max: 120, message: '订单名称3个字符以上，120个字符以内', trigger: 'blur' },
          { validator: validateChinese, trigger: 'blur' },
        ],
        productInfo: [{ required: true, message: '请输入产品信息', trigger: 'blur',},],
        orderType: [{ required: true, message: '请选择素材类型', trigger: 'change',},],
        displayMode: [{ required: true, message: '请选择展示形式', trigger: 'change',},],
        useType: [{ required: true, message: '请选择应用类型', trigger: 'change',},],
        specs: [{ required: true, message: '请输入规格尺寸', trigger: 'blur',},],
        expectFinishTime: [{ required: true, message: '请选择期望完成时间', trigger: 'change',},],
        costCenterNo: [
          { required: true, message: '请输入成本中心号', trigger: 'blur'},
          { validator: validateInteger, trigger: 'blur' }
          ],
        economyItem: [{ required: true, message: '请输入经济事项', trigger: 'blur',},]
      },
      makeInfoRoles:{
        designArrange: [],
        designer: [],
        designSupplier: [],
        designerCost: [{ required: true, message: '请输入制作服务费', trigger: 'blur',},],
        makeWay: [{ required: true, message: '请选择制作方式', trigger: 'change',},],
        planFinishTime: [{ required: true, message: '请选择计划完成时间', trigger: 'change',},],
        workingHours: [{ required: true, message: '请输入标准工时', trigger: 'blur',},],
        modifyTimes: [{ required: true, message: '请输入修改次数', trigger: 'change',},],
      },
      designArrangeRule:[{ required: true, message: '请选择设计安排', trigger: 'change',}],
      designerRule:[{ required: true, message: '请选择内部设计师', trigger: 'change',}],
      designSupplierRule:[{ required: true, message: '请选择设计单位', trigger: 'change',}],
      showMakeInfo:false,//显示制作信息
      // 附件上传
      fileColumns: [
        {title: '附件名称',dataIndex: 'fileName',scopedSlots: { customRender: 'fileName' }},
        {title: '文件大小',dataIndex: 'size',width: 150,align: 'center',customRender:function (text) {return formatSize(text)}},
        {title: '上传人',dataIndex: 'uploaderName',width: 150,align: 'center',},
        {title: '上传时间',dataIndex: 'uploadTime',width: 230,align: 'center',},
      ],
      fileData: [],
      showFileBtn:true,
      selectedRowKeys: [],
      selectionRows: [],
      tabLoading: false,
      showMediaFileDownload:false,
      // 评价
      rateDesc: ['非常满意', '不满意', '一般', '比较满意', '非常满意'],
      // 搜索项目负责人
      userTestData: [],
      fetching: false,
      isCanEdit:false ,
      url: {
        getUserList: '/lib/hteFileClass/getUserListOnlyUpms',
        queryOrderById:'/hteLibMediaOrder/queryById',
        saveOrder:'/hteLibMediaOrder/saveOrder',
        delBatch:'/hteLibMediaOrder/delBatch',
        submitOrder:'/hteLibMediaOrder/submitOrder',
        submitEvaluate:'/hteLibMediaOrder/submitEvaluate',
        downLoadBatch:'/common/downLoadBatchWithFileName',
        getMouldAttachId:"/hteLibMediaOrder/getMouldAttachId",
        getDepLeader:"/depInfo/getDepLeader",
        getDesigningCount: "/hteLibMediaOrder/getDesigningCount",
      },
      // 审批弹框
      userForm: {
        submitUserCols: [],
        proOriginTargetKeys: [], // 申请部门主管默认值
      },
      submitFlow:false,
      designingCount:0,
    }
  },
  mounted() {
    this.isMediaAdmin=filterHasPermission('libMedia:fullPower:all')||filterHasPermission('libMedia:fullPower:sj')||filterHasPermission('libMedia:fullPower:sp')||filterHasPermission('libMedia:fullPower:ds');
    this.initDics();
    if(!this.id){
      this.rules=this.baseInfoRules;
      this.form.applyUserId=this.userinfo.info.username;
      this.form.applyUserName=this.userinfo.info.realname;
      this.form.applyDeptId=this.userinfo.info.deptId;
      this.form.applyDeptName=this.userinfo.info.deptName;
      this.form.applyInfo=this.form.applyUserName+'/'+this.form.applyDeptName;
      this.saveBtnShow=true;
    }else{
      window.location.replace(this.MEDIA_BASE_URL + `/blank?hteToken=${Vue.ls.get(ACCESS_TOKEN)}&backUrl=` + encodeURI("/material/indentInfo?id="+this.id));
      this.initOrder();
    }
    this.getDepLeader();
  },
  methods: {
    initDics(){
      codeInfoList({type:'素材-订单类型',pageSize:-1,isdel: 0}).then((res) => {
        if (res.code == 200) {
          this.dict.orderTypeList = res.result.records
        } else {
          this.$message.warning('操作异常:' + res.message)
        }
      }).catch((res) => {
          this.$message.warning('操作异常:' + res.message)
      });
    },
    initOrder(){
      getAction(this.url.queryOrderById, {id:this.id}).then((res) => {
        if (res.code == 200) {
          this.form=res.result;
          this.form.applyInfo=this.form.applyUserName+'/'+this.form.applyDeptName;


          if (this.form.orderType){
            let obj = {}

            for (let i = 0 ; i < this.dict.orderTypeList.length ; i++){
              if (this.dict.orderTypeList[i].code === this.form.orderType){
                obj =  this.dict.orderTypeList[i]
              }
              if (['平面设计审核' , '视频制作审核'].includes(obj.name)){
                this.isCanUploadMaterial = true
              }
            }
          }
          if(this.form.processInstanceId){
            this.processInstanceId=this.form.processInstanceId;
          }
          this.initShowMakeInfo();
          this.submitBtnShow = this.form.status
            && ([1,6].indexOf(this.form.status)>-1)
            && this.form.applyUserId==this.options.userId;
          this.showFileBtn=
            this.form.status && this.form.status<5
            && (this.form.applyUserId==this.options.userId
            || this.form.auditUserIds
              &&this.form.auditUserIds.indexOf(this.options.userId)>=0
              ||this.form.copyForUserIds
              &&this.form.copyForUserIds.indexOf(this.options.userId)>=0);
          if(this.form.orderType){
            this.initDisplayAndUseType(this.form.orderType);
          }
          if(this.form.status>1&&this.form.status< 6){
            this.getDesigningCount();
          }
        } else {
          this.$message.warning('查询失败:' + res.message)
        }
      })
    },
    getDepLeader(){
      getAction(this.url.getDepLeader, {id:this.userinfo.info.deptId}).then((res) => {
        if (res.code == 200) {
          this.depLeader=res.result;
        } else {
          this.$message.warning('查询失败:' + res.message)
        }
      })
    },
    initDisplayAndUseType(parent){
      codeInfoByTypeAndParent({type:'素材-制作内容',parent:parent}).then((res) => {
        if (res.code == 200) {
          this.dict.displayModeList = res.result||[];
        } else {
          this.$message.warning('操作异常:' + res.message)
        }
      }).catch((res) => {
        this.$message.warning('操作异常:' + res.message)
      })
      codeInfoByTypeAndParent({type:'素材-应用渠道',parent:parent}).then((res) => {
        if (res.code == 200) {
          this.dict.useTypeList = res.result||[];
        } else {
          this.$message.warning('操作异常:' + res.message)
        }
      }).catch((res) => {
        this.$message.warning('操作异常:' + res.message)
      })
    },
    initShowMakeInfo(){
      const vm=this;
      this.showMakeInfo=this.form.status>1;
      if(this.form.status == 3){
        this.makeInfoRoles.designArrange=this.designArrangeRule;
        if(this.form.designArrange=='1'){
          this.makeInfoRoles.designer=this.designerRule;
        }
        if(this.form.designArrange=='2'){
          this.makeInfoRoles.designSupplier=this.designSupplierRule;
        }
      }
      if(this.form.status==1){
        this.rules=this.baseInfoRules;
      }else if(this.form.status==2||this.form.status==3){
        if(this.form.orderType=='3'){
          this.makeInfoRoles.designerCost=[];
        }
        this.rules=this.makeInfoRoles
      }else{
        this.rules={}
      }
      this.isCanEdit = ([1,6].indexOf(vm.form.status)>-1 ||  vm.form.isBackRevise)&&(vm.form.applyUserId==vm.options.userId)
      this.saveBtnShow=!vm.form.status || this.isCanEdit ||
        (vm.form.status==2&&(vm.currentTaskDefKey=='mediaAdmin'||vm.currentTaskDefKey=='eCommerceAdmin')&&vm.currentAuditUser==vm.options.userId||
          vm.form.status==3&&vm.currentAuditUser==vm.options.userId&&(vm.currentTaskDefKey=='orderDispatch'||vm.currentTaskDefKey=='mediaMaking'));


      vm.evaluateBtnShow=vm.form.status&&vm.form.status==4&&vm.currentAuditUser==vm.form.applyUserId&&vm.currentTaskDefKey=='submitConfirm';


      vm.showMediaFileDownload=vm.form.applyUserId==vm.options.userId||vm.form.auditUserIds&&vm.form.auditUserIds.indexOf(vm.options.userId)>=0||vm.form.copyForUserIds&&vm.form.copyForUserIds.indexOf(vm.options.userId)>=0;
      vm.delBtnShow=vm.form.status==1&&(vm.form.applyUserId==vm.options.userId||(this.isMediaAdmin&&!vm.form.processInstanceId))
    },

    orderTypeChange(value ){
      let obj = {}
      obj = this.dict.orderTypeList.map( item => {
        if (value === item.code){
          return item;
        }
      })
      if (['平面设计审核' , '视频制作审核'].includes(obj.name)){
        this.isCanUploadMaterial = true
      }
      this.$set(this.form,'displayMode','');
      this.$set(this.form,'useType','');
      this.initDisplayAndUseType(value);
    },
    designArrangeChange(e){
      if(this.form.designArrange=='1'){
        this.rules.designer=this.designerRule;
        this.rules.designSupplier=[];
      }
      if(this.form.designArrange=='2'){
        this.rules.designer=[];
        this.rules.designSupplier=this.designSupplierRule;
      }
    },
    /**
     * 上传附件
     */
    beforUpload(file, type){
      const that = this;
      let fileName= file.name
      const flag = this[type].some(item=>{
        return item.fileName == fileName
      })
      if(flag){
        that.$message.warning(`【${fileName}】文件名重复`);
        return false
      }
      return true
    },

    /**
     * 附件操作
     */
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },

    /**
     * 素材操作
     */
    handAction(type){
      if(type == 'add'){
        // 入库
      }
      if(type == 'downloadMould'){
        // 下载模板
        if(!this.form.orderType){
          this.$message.warning('请选择素材类型！');
          return;
        }
        this.downLoadMould();
      }
      if(type == 'download'){
        // 下载
        if(this.selectionRows.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        let attachIds=this.selectedRowKeys.join(",");
        this.doDownLoadBatch(attachIds);
      }
      if(type == 'del'){
        // 删除
        if(this.selectionRows.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        const that = this;
        if(this.selectionRows.some(f=>f.uploader!=that.options.userId)){
          this.$message.warning('只能删除自己上传的附件！');
          return;
        }
        Modal.confirm({
          title: '请确认是否删除此附件?',
          onOk: function() {
            for (let i = that.selectionRows.length - 1; i > -1; i--) {
              const rowIndex = that.selectionRows[i] ;
              const obj = that.selectionRows.find(item=>item.id == rowIndex.id)
              that.$refs['myUpload'].delete(obj);
            }
            that.selectedRowKeys = []
          }
        });
      }
    },
    downLoadMould(){
      getAction(this.url.getMouldAttachId, {orderType:this.form.orderType}).then((res) => {
        if (res.code == 200) {
          if(!res.result){
            this.$message.warning('没有相应的模板，请联系系统管理员维护');
            return;
          }
          let url=this.HTE_OLD_SERVER_URL+`/projectContractMould/download?bootToken=${Vue.ls.get(ACCESS_TOKEN)}&id=`+res.result;
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
        } else {
          this.$message.warning('获取模板失败:' + res.message)
        }
      }).catch((res) => {
        this.$message.warning('获取模板失败:' + res.message)
      })

    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame');
      iframe.src = this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)+'&zipFileName='+encodeURIComponent(this.form.orderNo+'附件.zip');
    },
    /**
     * 搜索项目负责人/内部设计师
     */
    fetchTestUser(val) {
      if (val) {
        this.userTestData = []
        this.fetching = true
        getAction(this.url.getUserList, { name: val }).then((res) => {
          if (res.success) {
            this.userTestData = res.result
            this.fetching = false
          }
        })
      }
    },
    fetchTestChange(value, option, name, id) {
      this.$set(this.form, id, value)
      this.$set(this.form, name, option.componentOptions.children[0].text.trim())
    },
    /**
     * 提交审批
     */
    onSubmitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if(!this.fileData.length){
            this.$message.warning(`请先上传附件`);
            return
          }
          this.$set(this.userForm, 'submitUserCols', [
            { label: '申请部门主管', field: 'applyDeptLeaderUser', username: this.depLeader?this.depLeader.oneaccount:'', realname: this.depLeader?this.depLeader.empname:'', required: true,},
          ]);
          if(this.form.orderType=='3'){
            this.userForm.submitUserCols.push({
              label: '新零售中台审核', field: 'needNewRetailCenter',type:'radio',required: true,username:'',
              options:[{value:"true",label:'需要'},{value:"false",label:'不需要'}]
            })
          }
          this.$refs.processUserSelect.doSelect();
        } else {
          return false;
        }
      });
    },
    onResetForm() {
      this.$refs.ruleForm.resetFields();
    },
    selectUserConfirm(result) {
      if (!result || result.length == 0) {
        return
      }
      let data = {};
      result.forEach((item) => {
        let key = item.field;
        data[key] = item.username
      });
      this.doSubmit(data);
    },
    doSubmit(data){
      const that = this;
      Modal.confirm({
        title: '请确认提交制作订单?',
        onOk: function() {
          that.btnLoading=true;
          that.form.approvalPerson=data;
          postAction(that.url.submitOrder, that.form).then((res) => {
            that.btnLoading=false;
            if (res.code == 200) {
              that.$message.success(`提交成功`);
              // this.$router.push("/library/media/addOrder?id="+that.form.id)
              that.initOrder();
            } else {
              that.$message.warning('提交失败:' + res.message)
            }
          })
        }
      });
    },
    saveData(){
      const vm=this;
      if(this.form.status>1){
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            vm.doSaveData();
          }else{
            document.getElementById("makeInfoDiv").scrollIntoView(true)
          }
        });
      }else{
        this.doSaveData();
      }
    },
    doSaveData(){
      this.btnLoading=true;
      postAction(this.url.saveOrder, this.form).then((res) => {
        this.btnLoading=false;
        if (res.code == 200) {
          let id=res.result;
          this.$message.success(`保存成功`);
          if(!this.id){
            this.id=id;
            this.initOrder();
            if(window.parentReload){
              window.parentReload("{}")
            }else{
              window.opener.location.reload();
            }
            this.$router.push({ path: '/library/media/addOrder?id='+id }).catch(() => {
              console.log('登录跳转首页出错,这个错误从哪里来的')
            })
          }
          if(this.submitFlow&&this.saveBtnShow){
            this.$refs.childrenRef.submitTaskNotBefore();
          }
        } else {
          this.submitFlow=false;
          this.$message.warning('保存失败:' + res.message)
        }
      })
    },
    onSubmitEvaluate(){
      if(!this.form.evaluationScore){
        this.$message.warning("请先进行评分再提交")
        return;
      }
      if(this.form.evaluationScore<=3&&(!this.form.suggestion||this.form.suggestion.trim()=='')){
        this.$message.warning("您给的评分较低，请留下您的宝贵意见再提交")
        return;
      }
      const that = this;
      that.btnLoading=true;
      postAction(that.url.submitEvaluate, that.form).then((res) => {
        that.btnLoading=false;
        if (res.code == 200) {
          that.$message.success(`提交成功`);
          that.initOrder();
          if(this.submitFlow){
            this.$refs.childrenRef.submitTaskNotBefore();
          }
        } else {
          this.submitFlow=false;
          that.$message.warning('提交评价数据失败:' + res.message)
        }
      })
    },
    deleteOrder(){
      const that=this;
      Modal.confirm({
        title: '请确认删除制作订单?',
        onOk: function() {
          postAction(that.url.delBatch, [that.form.id]).then((res) => {
            if (res.code == 200) {
              that.$message.success('删除成功')
              if(window.parentReload){
                window.parentReload("{}")
              }else{
                window.opener.location.reload();
              }
              setTimeout(() => {
                window.CloseCefTab ? window.CloseCefTab():window.close();
              }, 1000);
            } else {
              that.$message.warning('删除失败:' + res.message)
            }
          })
        }
      });
    },
    previewAttach(attach){
      if(isPreview(attach.fileName)){
        previewAttach(attach).then(result=>{
          const url=URL.createObjectURL(result)
          window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
        }).catch(err => {
          this.$message.warning('下载文件失败');
        })
      }else{
        let href =
          this.API_BASE_URL +'/tp/attach/download?id=' +
          attach.id +
          '&dbKey=Trd&ftpKey='+attach.ftpKey+'&token=' +
          Vue.ls.get(ACCESS_TOKEN)+'&fullfilename='+attach.fileName
        window.open(process.env.VUE_APP_ONLINE_BASE_URL+'?url='+encodeURIComponent(Base64.encode(href)));
      }
    },
    remainSave(){
      this.$message.warning('请先保存数据再上传附件！');
    },
    getDesigningCount(){
      getAction(this.url.getDesigningCount,{orderId:this.form.id}).then((res) => {
        if (res.code == 200) {
          this.designingCount=res.result||0;
        } else {
          this.$message.warning('获取制作中数量失败:' + res.message)
        }
      })
    },
    //-------------流程回调------start
    beforeSubmit(res) {
      //设计师步骤必须上传素材文件
      if(this.currentTaskDefKey=='mediaMaking'){
        let mediaFiles=this.$refs.mediaAttach.getFiles();
        if(!mediaFiles||mediaFiles.length===0){
          this.$message.warning('请先上传素材文件再提交')
          return false;
        }
      }
      if (this.form.isBackRevise == 1 && this.currentTaskDefKey=='mediaMaking'){
        this.lawVisible = true;
        return false
      }
      if (this.currentTaskDefKey == 'orderDispatch'){
        if (!this.form.designArrange  && (!this.form.designerName || !this.form.designSupplier)){
          this.$message.warning('请先填写设计信息。【设计安排 、设计单位、内部设计师】')
          return false;
        }
      }
      this.submitFlow = true;
      if(this.saveBtnShow){
        this.saveData();
        return false;
      }
      if(this.evaluateBtnShow){
        this.onSubmitEvaluate();
        return false;
      }
      return true
    },
    handleConfirm(value){
      if (value == 1){
        this.$set(this.form , 'modifyTimes' , this.form.modifyTimes + 1)
        this.doSaveData();
      }
      this.$refs.childrenRef.submitTaskNotBefore();
      this.lawVisible = false
    } ,
    afterSubmit(res)
    {
      this.submitFlow=false;
      this.currentTaskDefKey = '';
      this.currentAuditUser='';
      this.initOrder();

      // this.$set(this.form , 'isBackRevise' , 0)
      // this.doSaveData()
      return true;
    },
    beforeReject(res)
    {
      // 驳回前置动作
      return !!this.checkOptionValue();
    },
    afterReject(res)
    {
      // this.$set(this.form , 'isBackRevise' , 1)
      // this.doSaveData()
      // 用户点击驳回后成功返回后的处理
    },
    backAction(res)
    {
      // this.makeInfoRoles.designArrange = [];
      // this.$set(this.form , 'isBackRevise' , 1)
      // this.doSaveData()
      return true;
    },
    //撤回后
    afterCancelSubmit() {
      return true;
    },
    // 生成抄送任务方法，非必须
    sendNotify() {
      // 参数一：抄送人，参数二：工作台打开详情链接
      // this.$refs.childrenRef.saveBpmNotify('liangyh', 'http://xxxxx.com')
    },
    saveNotifyOpinion() {
      // 保存抄送意见前置动作
      return true;
    },
    taskLoad(task) {
      this.currentTaskDefKey = task.taskDefKey;
      this.currentAuditUser=task.currentUserId;


      // if (this.currentTaskDefKey == 'submit'){
      //   this.$set(this.form , 'status' , 1)
      //   this.$set(this.form , 'statusOrder' , 4)
      //   this.doSaveData()
      // }

      // if (this.currentTaskDefKey == )
      this.initShowMakeInfo();
    },
    checkOptionValue() {

      var options = this.$refs.childrenRef.data
      if (options == '' || options == null || options == undefined) {
        this.$message.warning('审批意见不能为空', 3000)
        return false
      } else {
        return true
      }
    },
    //-------------流程回调------end
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.cr-content-pop {
  p {margin-bottom: 15px;color: #666;
    &:hover{color: @bg-color-btn;}
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.em{font-size: 12px;color: #f5222d;margin-left: 5px;}
/deep/ .ant-input-number{width: 100%;}
.mt15{margin-top:25px}
.ratebox{top: -3px;display: inline-block;}
.btn-line{display: flex;}

/deep/ #process-container {
  width:100% !important;
}
</style>
